<?php
/**
 * 用户管理
 */
namespace Admin\Controller;
use Admin\BaseController;
use Admin\Model\AddressModel;
use Common\Model\EventsModel;
use Common\Model\NoticeModel;
use Common\Model\UserModel;
use Common\Model\UtilsModel;
use Common\Model\SmsModel;
use Common\Model\LogModel;
use Think\Page;
class UserController extends BaseController{
	/**
	 * 用户列表
	 * Author: shijy
	 */
	public function index(){

		$vip=I('get.vip',0,'int');
		$status=I('get.status',0,'int');
		$where='1';
		if($vip>0){
			$where .=" and vip={$vip}";
		}

		if($status>0){
			$where .=" and userStatus={$status}";
		}

		$userNameOrNickName=I('get.userNameOrNickName',null);
		if($userNameOrNickName){
			$where .=" and (uid = '{$userNameOrNickName}' or nickname like '%{$userNameOrNickName}%' )";
		}


		$realName=I('get.realName',null);
		if($realName){
			$where .=" and realName like '{$realName}'";
		}

		$phone=I('get.phone');
		if($phone){
			$where .=" and bindPhone like '%{$phone}%'";
		}

		$beginTimeStr	=I('get.beginTime');
		$endTimeStr		=I('get.endTime');

		$beginTime=strtotime($beginTimeStr);
		$endTime=strtotime($endTimeStr);
		if($beginTime>0){
			$where .=" and regTime >= $beginTime";
		}

		if($endTime>0){
			$where .=" and regTime <= $endTime";
		}



		$ofield=I('get.ofield');
		$otype=I('get.otype','');

		if(strcmp($otype,'')==0) {
			$field=null;
		}else{
			switch($ofield){
				case 1:
					$field='uid';
					break;
				case 2:
					$field='regFrom';
					break;
				case 3:
					$field='userName';
					break;
				case 4:
					$field='nickname';
					break;
				case 5:
					$field='realName';
					break;
				case 6:
					$field='bindPhone';
					break;
				case 7:
					$field='point';
					break;
				case 8:
					$field='vip';
					break;
				case 9:
					$field='regTime';
					break;
				default:
					$field=null;
			}
		}


		if($field){
			$order="{$field} {$otype}";
		}else{
			$order=null;
		}



		$userM = M("u_user_base",null,DB_MAIN_CFG);

		$count = $userM->where($where)->count();
		$this->smarty->assign('totalDataCount',$count);

		$limit = I('get.limit',10,'int');	//每页显示条数
		$Page = new Page($count,$limit);
		fetchPage($this->smarty,$Page);

		
		
		if($order) {
			$list = $userM->where($where)->order($order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
		}else{
			$list = $userM->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->select();
		}

		$uidstr='0';
		foreach ($list as $v){
			$uidstr .=','.$v['uid'];
		}
		if (strcmp($uidstr,'0')!=0){
			$usedVips=EventsModel::getJoinInstance()->where("uid in({$uidstr}) and useVip=1")->group("uid")->getField("uid,count(1)",true);
			if (count($usedVips)>0) {
				foreach ($list as $k=>$v) {
					if (array_key_exists($v['uid'],$usedVips)){
						$list[$k]['usedVipCount']=$usedVips[$v['uid']];
					}
				}
			}
		}

		

		$this->smarty->assign('limit',$limit);
		$this->smarty->assign('ofield',$ofield);
		$this->smarty->assign('otype',$otype);

		$vipKV=getVipKv();
		$this->smarty->assign('vipKV',$vipKV);
		$this->smarty->assign('selectedVIP',$vip);

		$this->smarty->assign('status',UserModel::getUserStatus());//C('USER_STATUS'));
		$this->smarty->assign('selectedStatus',$status);

		$this->smarty->assign('userNameOrNickName',$userNameOrNickName);
		$this->smarty->assign('realName',$realName);
		$this->smarty->assign('phone',$phone);

		$this->smarty->assign('beginTime',$beginTimeStr);
		$this->smarty->assign('endTime',$endTimeStr);

		$this->smarty->assign('list',$list);

		$this->smarty->display('User/index.html');
	}

	/**
	 * vip设置
	 */
	public function editVip(){
		$uid=I('get.uid',0,'int');
		if($uid<=0){
			$this->error("请指定用户");
		}
		$vipInfo=UserModel::getUserVipInfo($uid);
		$this->smarty->assign('obj',$vipInfo);
		$this->smarty->assign('uid',$uid);
		$this->smarty->display('User/editVip.html');
	}


	public function updateVip(){
		$uid=I('get.uid',0,'int');
		if($uid<=0){
			$this->error("请指定用户");
		}
		$times=I('post.times',0,'int');
		if ($times<=0){
			UserModel::getInstance()->startTrans();
			if(UserModel::getInstance()->where("uid={$uid}")->save(array("vipEndTime"=>0,"vipEventJoinTimes"=>0,'vip'=>0))!=false){
				if(false==UserModel::getVipLogInstance()->add(array("uid"=>$uid,"addTime"=>time(),"act"=>'后台清零VIP'))){
					UserModel::getInstance()->rollback();
					$this->error("设置失败");
				}
				else{
					UserModel::getInstance()->commit();
					$this->success("设置成功");
				}
			}else{
				$this->success("设置成功");
			}
		}else{
			$now=time();
			$VipInfo=UserModel::getUserVipInfo($uid);
			if ($VipInfo['vip']==0 || $VipInfo['vipEventJoinTimes']<=0 ||$VipInfo['vipEndTime']<=$now){
				$endTime=$now+366*UtilsModel::ONE_DAY;
				$VipInfo['vipEndTime']=$endTime;
			}
			$log="后台设置次数{$VipInfo['vipEventJoinTimes']} -> {$times}";
			$VipInfo['vipEventJoinTimes']=$times;
			$VipInfo['vip']=1;
			UserModel::getInstance()->where("uid={$uid}")->save($VipInfo);
			UserModel::getVipLogInstance()->add(array("uid"=>$uid,"addTime"=>time(),"act"=>$log));
			$this->success("设置成功");
		}
	}

	

	public function edit(){
		$uid=I('get.uid',0,'int');
		if($uid<=0){
			$this->error("请指定用户");
		}

		$userM=M('u_user_base',null,DB_MAIN_CFG);
		$uinfo=$userM->where("uid={$uid}")->find();
		if(!$uinfo){
			$this->error("指定用户数据并不存在");
		}

		$tagKV=getUTagKv();
		$this->smarty->assign('tag',$tagKV);
		
		$provinceKV = include_once(WEB_ROOT.'/data/area_info/area_province_list.php');
		$this->smarty->assign('province',$provinceKV);
		
		$addStr = UtilsModel::getRegionNameByProvince($uinfo,'/');
		$this->smarty->assign('address',$addStr);

		$this->smarty->assign('obj',$uinfo);
		$this->smarty->display('User/edit.html');
	}
	//获取下一级地址数据
	public function getArea_info(){
		$area_id = I('post.area_id',0,'int');
		$level = I('post.level',0,'int');
		$provinceID = I('post.provinceID',0,'int');

		$areaArr = AddressModel::getArea_info($area_id,$level,$provinceID);

		$this->smarty->assign('add',$areaArr);
		$html = $this->smarty->fetch("User/address.html");
		$return['dataHtml'] = $html;
		$this->ajaxReturn($return);
	}
	//修改用户信息
	public function update(){
		$uid=I('get.uid',0,'int');
		if($uid==0){
			$this->error("请指定用户编号");
		}

		$nickName=I('post.nickname');
		$nickLen=UtilsModel::strlen($nickName);

		if($nickLen<C('NICKNAME_LENGTH_MIN') or $nickLen>C('NICKNAME_LENGTH_MAX')){
			$this->error('昵称长度不符合要求：'.C('minNickLen').' - '.C('maxNickLen'));
		}

		$tag=I('post.tag',1,'int');

		$realName=I('post.realName',null);
		if(!$realName){
			$this->error("真实姓名填写错误");
		}

		$province=I('post.province',0,'int');
		$city=I('post.city',0,'int');
		$district=I('post.district',0,'int');
		$street=I('post.street',0,'int');
		$address=I('post.address');

		$sex=I('post.sex',3,'int');
		$birthday=I('post.birthday');

		$userM=M('u_user_base',null,DB_MAIN_CFG);
		$updateData=array(
			'nickname'=>$nickName,
			'realName'=>$realName,
			'userTag'=>$tag,
			'province'=>$province,
			'city'=>$city,
			'district'=>$district,
			'street'=>$street,
			'address'=>$address,
			'sex'=>$sex,
			'birthday'=>$birthday
		);
		$userM->where("uid={$uid}")->save($updateData);

		if (IS_BROADCAST) {
			$postData = array(
				'user_id' => $uid,
				'nickname' => $nickName,
				'name' => $realName,
				'sex' => $sex,
				'province_id'=>$province,
				'area_id'=>$city,
				'discrict_id'=>$district,
				'street_id'=>$street,
				'address' => $address,
				'birthday' => $birthday,
			);
			LogModel::dailyLog('up_user', $postData);
			UtilsModel::broadcast('up_user',$postData);
		}

		$this->success("数据修改成功");

	}


	//用户操作
	public function operation(){
		$this->smarty->display('User/shutup.html');
	}

	public function shutup(){
		$uidstr=I('post.uid');
		$uidArr=explode(',',$uidstr);
		foreach($uidArr as $k=>$v){
			if($v+0 <1){
				unset($uidArr[$k]);
			}
		}

		$uidstr=implode(',',$uidArr);

		$operation=I('post.operation',0,'int');
		switch($operation){
			case 1:
				$content=I('post.contentWarning');
				break;
			case 2:
				$content=I('post.contentDeny');
				break;
			default:
				$this->error('请选择操作类型！');
				break;
		}
		if(UtilsModel::strlen($content)==0){
			$this->error('请输入消息内容！');
		}

		//禁言操作
		if($operation==2){
			$userM=M('u_user_base',null,DB_MAIN_CFG);
			$uinfoArr=$userM->where("uid in ({$uidstr})")->setField("userStatus",UserModel::USER_STATUS_SHUTUP);
		}
		$this->success("操作成功！");
	}

	/**
	 * function point 用户积分页面
	 * function pointDO 用户积分处理action
	 */
	public function point(){
		$this->smarty->display('User/point.html');
	}
	public function pointDo(){
		$all=I('post.all',0,'int');
		$pointAdd=I('post.pointAdd/d',0,'int');
		$pointReduce=I('post.pointReduce/d',0,'int');
		$msg=I('post.msg',null,'trim');
		$title=I('post.title');
		$index=I('post.index',1,'int');
		$currentRowsCount=100;//每次处理数据条数

		$userM=M('u_user_base',null,DB_MAIN_CFG);

		if($all==0){//不是全部
			$uidstr=I('post.uid');
			$uidArr=explode(',',$uidstr);
			foreach($uidArr as $k=>$v){
				if($v+0 <1){
					unset($uidArr[$k]);
				}
			}
			$count = count($uidArr);
			if($count<1){
				$this->ajaxReturn(array('status'=>0,'msg'=>"请输入有效的用户ID"));
			}

			if($count < $currentRowsCount){
				$res = self::batchExecutive($uidArr,$pointAdd,$pointReduce,$title,$msg);
				$offset = 0;$currentRowsCount = $count;
			} else{
				$offset = ($index-1)*$currentRowsCount;
				$page = max(1,ceil($count/$currentRowsCount));
				$nextPage = $index >= $page ? 0:1;
				if(($count-$offset) < $currentRowsCount){
					$currentRowsCount = $count-$offset;
				}

				$doUidArr = array_slice($uidArr,$offset,$currentRowsCount);
				$res = self::batchExecutive($doUidArr,$pointAdd,$pointReduce,$title,$msg,$nextPage);
			}
			if($res['status'] == 0){
				$this->ajaxReturn($res);
			}else if($res['status'] ==2){
				$dealNum = $offset+$currentRowsCount;
				$res['msg'] = "共有".$count."条数据，已成功存入".$dealNum."条，进度条正在狂奔，请稍后……";
			}

		}else{//全服，不会扣减
			if($pointAdd<=0){
				$this->error("请输入增加的积分数量");
			}
			$uidArr = $userM->getField("uid",true);
			$count = count($uidArr);
			$offset = ($index-1)*$currentRowsCount;
			$page = max(1,ceil($count/$currentRowsCount));
			$nextPage = $index >= $page ? 0:1;
			if(($count-$offset) < $currentRowsCount){
				$currentRowsCount = $count-$offset;
			}
			$doUidArr = array_slice($uidArr,$offset,$currentRowsCount);

			foreach($doUidArr as $val){
				UserModel::plusPoint($val,-1,$pointAdd,OPT_ADMIN_PLUS_POINT);
			}
			if($nextPage){
				$dealNum = $offset+$currentRowsCount;
				$res = array('status'=>2,'msg'=>"共有".$count."条数据，已成功存入".$dealNum."条，进度条正在狂奔，请稍后……");
			} else{
				$res =array('status'=>1,'msg'=>"积分操作成功");
				$data = NoticeModel::saveSystemNotice($title,$msg);
				if($data['status']==0){
					session('noticeFlag',1);
				}
			}
		}

		$reason=I('post.reason');
		$this->log($reason);
		$this->ajaxReturn($res);
	}

	/**
	 * 批量执行
	 */
	public function batchExecutive($uidArr,$pointAdd,$pointReduce,$title,$msg,$nexPage=0){
		$return = array('status'=>1,'msg'=>"积分操作成功");
		if($nexPage){
			$return = array('status'=>2);
		}
		if($pointAdd>0){
			foreach($uidArr as $val){
				UserModel::plusPoint($val,-1,$pointAdd,OPT_ADMIN_PLUS_POINT);
				NoticeModel::saveNotice(NoticeModel::NOTICE_TYPE_SYSTEM_MSG,0,0,0,$val,$title,$msg);
			}
		}elseif($pointReduce>0){
			foreach($uidArr as $val){
				UserModel::minusPoint($val,-1,$pointReduce,OPT_ADMIN_MINUS_POINT);
				NoticeModel::saveNotice(NoticeModel::NOTICE_TYPE_SYSTEM_MSG,0,0,0,$val,$title,$msg);
			}
		}else{
			$return = array('status'=>0,'msg'=>"请输入有效积分数值");
		}
		return $return;
	}

	/**
	 *	function sms 发送短信
	 * 	function sendSms
	 */
	public function sms(){
		$tplKv=SmsModel::getSmsTpl();
		$this->smarty->assign('tplKv',$tplKv);
		$this->smarty->display('User/sms.html');
	}
    public function sendSms(){
        $phone = I("get.phone",'','trim');
        $tpl = I("get.tpl",'','trim');

        if(!$phone ){
            $this->ajaxReturn( array('status'=>1, 'msg'=>'请填写手机号') );
        }

		unset($_GET['phone']);
		unset($_GET['m']);
		unset($_GET['c']);
		unset($_GET['a']);
		unset($_GET['tpl']);

        $data = SmsModel::sendSms($phone,$tpl,$_GET);
        $this->ajaxReturn( $data );

    }
	/**
	 *	function notice 发送通知
	 * 	function sendMessage
	 */
	public function notice(){
		$this->smarty->display('User/notice.html');
	}
	public function sendMessage(){
		$uidstr = I("get.uid",'','trim');
		$all = I("get.all",0,'intval');
		$title = I("get.title",null,'trim');

		$content = I("get.content",'','trim');
		$link = I("get.link",'','trim');
		if(!$uidstr && !$all){
			$this->ajaxReturn(array('status'=>1,'msg'=>'请填写用户ID或全部发送'));
		}
		if($all==0){
			$uidArr = explode(',',$uidstr);
			foreach($uidArr as $k=>$v){
				if($v+0 <1){
					unset($uidArr[$k]);
				}
				$data=NoticeModel::saveNotice(NoticeModel::NOTICE_TYPE_SYSTEM_MSG,0,0,0,$v,$title,$content,$link);
			}
			if(count($uidArr)<1){
				$this->error("请输入有效的用户ID");
			}
		}
		else{
			$data = NoticeModel::saveSystemNotice($title,$content,$link);
			if($data['status']==0){
				session('noticeFlag',1);
			}
		}
			$this->ajaxReturn($data);
	}



}
